﻿using System.Collections.Generic;
using Castle.ActiveRecord;
using NHibernate.Criterion;

namespace WebConversion.Module
{
    public static class Repository
    {
        public static T Find<T>(int id)
        {
            var result = ActiveRecordBase<T>.Find(id);
            return result;
        }

        public static List<T> Find<T>(KeyValuePair<string, object> condition)
        {
            var criteria = DetachedCriteria.For<T>();
            criteria.Add(GetCondition(condition));

            var result = ActiveRecordBase<T>.FindAll(criteria);
            return new List<T>(result);
        }

        public static List<T> Find<T>(List<KeyValuePair<string, object>> conditions)
        {
            var criteria = DetachedCriteria.For<T>();
            conditions.ForEach(t=> criteria.Add(GetCondition(t)));
            
            var result = ActiveRecordBase<T>.FindAll(criteria);
            return new List<T>(result);
        }

        private static ICriterion GetCondition(KeyValuePair<string, object> condition)
        {
            return Restrictions.Eq(condition.Key, condition.Value);
        }

        public static List<T> List<T>()
        {
            var result = ActiveRecordBase<T>.FindAll();
            return new List<T>(result);
        }

        public static List<T> ListByProperty<T>(KeyValuePair<string, object> property)
        {
            var result = ActiveRecordBase<T>.FindAllByProperty(property.Key, property.Value);
            return new List<T>(result);
        }
    }
}
